package lee.meiriyiti.day1118;

import java.util.Stack;

public class TestDemo1118_2 {
    public static boolean isvalid(String str,int n) {
        Stack<Character> stack = new Stack<>();
        if (n==0||str==null)return false;
        for (int i = 0; i <n; i++) {
            char ch=str.charAt(i);
            if (ch== '(') {//将左括号放进栈里
                stack.push(ch);
            } else {
                if (stack.isEmpty()) {
                    return false;//栈为空，则说明只没有左括号
                }
                char ch1 = stack.peek();
                if (ch1=='('||ch==')'){
                    stack.pop();//左右括号匹配成功，弹出栈顶元素
                }else {
                    return false;//左右括号不匹配
                }
            }
        }
        if (!stack.isEmpty()){
            return false;//栈不为空，说明栈里还有左括号
        }
    return true;
    }
}
